#include "Thread.h"
#include <iostream>

CThread::CThread()
{
	m_arg = nullptr;
	printf("CThread()\n");
}

CThread::~CThread()
{
	Stop();
	printf("~CThread()\n");
}

void CThread::Start()
{
	std::cout << "CThread::Start()" << std::endl;
	M_bIsInterript = true;
	std::thread thr(std::bind(&CThread::Run, this));
	this->m_Th = std::move(thr);
	this->m_Th.detach();
}

#if 0
void CThread::Start(void* (*ThreadFun) (void*), void* arg)
{
	std::thread thr(std::bind(ThreadFun, arg));
	this->m_Th = std::move(thr);
}
#endif

void CThread::Start(const std::function<void()> func, void* arg)
{
	std::cout << "CThread::Start()" << std::endl;
	_func = func;
	m_arg = arg;
	M_bIsInterript = true;
	std::thread thr(std::bind(&CThread::Run, this));
	this->m_Th = std::move(thr);
//	this->m_Th.detach();;
}

void CThread::Start(const std::function<void()> func)
{
	std::cout << "CThread::Start()" << std::endl;
	_func = func;
	M_bIsInterript = true;
	std::thread thr(std::bind(func));
	this->m_Th = std::move(thr);
	//
//	this->m_Th.detach();
}

std::thread::id CThread::GetId()
{
	return this->m_Th.get_id();
}

void CThread::Interrupt()
{
	this->M_bIsInterript = false;
}

bool CThread::IsInterrupted()
{
	return this->M_bIsInterript;
}

void CThread::Stop()
{
	if (this->IsInterrupted())
	{
		this->Interrupt();
	}

	if (this->m_Th.joinable()) {
		this->m_Th.join();
	}
	printf("Stop()\n");
}

void CThread::Run()
{
	while (this->IsInterrupted())
	{
		if (_func)
		{
			_func();
		}
	}
}